//
//  ViewController.m
//  高德地图
//
//  Created by dllo on 15/9/23.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "ViewController.h"
#import <MAMapKit/MAMapKit.h>
#import "AsyncConnection.h"

#import "define.h"
static MAPointAnnotation *currentPoint = nil;

@interface ViewController ()<MAMapViewDelegate,UISearchBarDelegate>

@property (nonatomic, retain) MAMapView *mapView;
@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, retain) CLGeocoder *geocoder;
@property (nonatomic,retain)NSString *searchtext;
@property (nonatomic,retain)NSMutableArray *arr;
@property (nonatomic,retain)UILabel *maxlabel;
@property (nonatomic,retain)UILabel *minlabel;
@property (nonatomic,retain)UILabel *weatherlabel;
@property (nonatomic,retain)UILabel *flabel;
@property (nonatomic,retain)UIView *mview;
@property (nonatomic,retain)UILabel *alabel;
@property (nonatomic,retain)UILabel *blabel;
@property (nonatomic,retain)UILabel *clabel;
@property (nonatomic,retain)UILabel *dlabel;
@property (nonatomic,assign)int a;
@property (nonatomic,assign)int b;
@property (nonatomic,retain)UILabel *aalabel;
@property (nonatomic,retain)UILabel *bblabel;
@property (nonatomic,retain)UILabel *cclabel;
@property (nonatomic,retain)UILabel *locallabel;
@property (nonatomic,retain)UIButton *xbutton;
@property (nonatomic, assign) CGFloat offHeight;
@property (nonatomic, assign) CGFloat offWidth;
@end

@implementation ViewController

-(void)dealloc
{
    [super dealloc];
    [_arr release];
    [_mapView release];
    [_searchBar release];
    [_searchtext release];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.arr = [NSMutableArray array];
        self.offHeight = [UIScreen mainScreen].bounds.size.height / 667;
        self.offWidth = [UIScreen mainScreen].bounds.size.width / 375;
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.geocoder = [[CLGeocoder alloc] init];
    
    [self createMap];
    [self createMapView];
    self.a = 1;
    self.b = 1;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"f.png"] style:UIBarButtonItemStyleDone target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor darkGrayColor];
    
    if (self.localstr != nil) {
        
        [self addData];
        [self getCoordinateByAddress:self.localstr];
        
        
        
    }
}
- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

-(void)createMap
{
    [MAMapServices sharedServices].apiKey = @"8263eaa3ae66a82f5364ac7924cf5a1e";
    //  [NSString stringWithFormat:@"%@%@",weather,self.searchtext]
    
}

- (void)addData
{
    
    [self.arr removeAllObjects];
    if (self.localstr != nil) {
        self.searchtext = self.localstr;
        if ([self.searchtext isEqualToString:@"大连市"]) {
            self.searchtext = @"大连";
        }
        
    }
    else{
        self.searchtext = self.searchtext;
    }
    
    NSString *q = [NSString stringWithFormat:@"http://weather.lanrentianqi.com/data/otherWeather?city=%@",self.searchtext];
    
    [AsyncConnection asyncConnection:q parmaters:nil block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dictory = [dic objectForKey:@"result"];
        NSArray *arr = [dictory objectForKey:@"days"];
        if ([[arr class] isSubclassOfClass:[NSNull class]])
        {
            NSLog(@"没有此景点");
            
        }else
        {
            [self.arr addObjectsFromArray:arr];
            
            
            
            
            
            
            
            
            
            self.maxlabel.text = [NSString stringWithFormat:@"%@",[[self.arr objectAtIndex:0] objectForKey:@"maxTmp"]];
            self.minlabel.text = [NSString stringWithFormat:@"%@",[[self.arr objectAtIndex:0] objectForKey:@"minTmp"]];
            self.weatherlabel.text = [[self.arr objectAtIndex:0] objectForKey:@"sky"];
            self.flabel.text = [[self.arr objectAtIndex:0] objectForKey:@"wind"];
            
            
            
            
            
            
        }
        
    } path:nil];
    
}
- (void)buttonAction:(UIButton *)button
{
    _a = _a * (-1);
    if (_a == -1 ) {
        
        if (self.arr.count != 0) {
            
            
            
            self.alabel = [[UILabel alloc] initWithFrame:CGRectMake(-200 * _offWidth, 150 * _offHeight, 0, 0)];
            _alabel.backgroundColor = [UIColor colorWithWhite:0.7 alpha:0.7];
            _alabel.layer.cornerRadius = 8;
            _alabel.layer.masksToBounds = YES;
            _alabel.textColor = [UIColor whiteColor];
            _alabel.numberOfLines = 0;
            _alabel.font = [UIFont systemFontOfSize:20];
            _alabel.text =[NSString stringWithFormat:@"明日天气:%@ / %@",[[self.arr objectAtIndex:1] objectForKey:@"maxTmp"],[[self.arr objectAtIndex:1] objectForKey:@"minTmp"]];
            [self.view addSubview:_alabel];
            
            self.blabel = [[UILabel alloc] initWithFrame:CGRectMake(-200 * _offWidth, 180 * _offHeight, 0, 0)];
            _blabel.backgroundColor = [UIColor grayColor];
            _blabel.textColor = [UIColor whiteColor];
            _blabel.numberOfLines = 0;
            _blabel.backgroundColor = [UIColor colorWithWhite:0.7 alpha:0.7];
            _blabel.layer.cornerRadius = 8;
            _blabel.layer.masksToBounds = YES;
            _blabel.font = [UIFont systemFontOfSize:20];
            _blabel.text =[NSString stringWithFormat:@"%@  %@",[[self.arr objectAtIndex:1] objectForKey:@"sky"],[[self.arr objectAtIndex:1] objectForKey:@"wind"]];
            [self.view addSubview:_blabel];
            
            self.clabel = [[UILabel alloc] initWithFrame:CGRectMake(-200 * _offWidth, 240 * _offHeight, 0, 0)];
            _clabel.backgroundColor = [UIColor grayColor];
            _clabel.textColor = [UIColor whiteColor];
            _clabel.numberOfLines = 0;
            _clabel.backgroundColor = [UIColor colorWithWhite:0.7 alpha:0.7];
            _clabel.layer.cornerRadius = 8;
            _clabel.layer.masksToBounds = YES;
            _clabel.font = [UIFont systemFontOfSize:20];
            _clabel.text =[NSString stringWithFormat:@"后天天气:%@ / %@",[[self.arr objectAtIndex:2] objectForKey:@"maxTmp"],[[self.arr objectAtIndex:2] objectForKey:@"minTmp"]];
            [self.view addSubview:_clabel];
            
            self.dlabel = [[UILabel alloc] initWithFrame:CGRectMake(-200 * _offWidth, 260 * _offHeight, 0, 0)];
            _dlabel.backgroundColor = [UIColor grayColor];
            _dlabel.textColor = [UIColor whiteColor];
            _dlabel.numberOfLines = 0;
            _dlabel.backgroundColor = [UIColor colorWithWhite:0.7 alpha:0.7];
            _dlabel.layer.cornerRadius = 8;
            _dlabel.layer.masksToBounds = YES;
            _dlabel.font = [UIFont systemFontOfSize:20];
            _dlabel.text =[NSString stringWithFormat:@"%@  %@",[[self.arr objectAtIndex:2] objectForKey:@"sky"],[[self.arr objectAtIndex:2] objectForKey:@"wind"]];
            [self.view addSubview:_dlabel];
            
            
            
            
            
            [UIView animateWithDuration:0.5 animations:^{
                _alabel.frame = CGRectMake(160 * _offWidth, 160 * _offHeight, 200 * _offWidth, 50 * _offHeight);
            }];
            [UIView animateWithDuration:1 animations:^{
                _blabel.frame =   CGRectMake(160 * _offWidth, 220 * _offHeight, 200 * _offWidth, 50 * _offHeight);
            }];
            
            
            [UIView animateWithDuration:1.5 animations:^{
                _clabel.frame = CGRectMake(160 * _offWidth, 300 * _offHeight, 200 * _offWidth, 50 * _offHeight);
            }];
            [UIView animateWithDuration:2 animations:^{
                _dlabel.frame =   CGRectMake(160 * _offWidth, 360 * _offHeight, 200 * _offWidth, 50 * _offHeight);
            }];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有详情，请重新搜索" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
        
        
    }
    else
    {
        [_alabel removeFromSuperview];
        [_blabel removeFromSuperview];
        [_clabel removeFromSuperview];
        [_dlabel removeFromSuperview];
        
    }
    
    
    
    
    
}



-(void)createMapView
{
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height)];
    self.mapView.showTraffic = YES; // 路况
    [self.view addSubview:_mapView];
    self.mapView.delegate = self;
    self.mapView.showsUserLocation = YES;
    [self.mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    
    [_mapView release];
    
    
    UIView *mapview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64  * _offHeight)];
    mapview.backgroundColor = [UIColor clearColor];
    self.navigationItem.titleView = mapview;
    mapview.layer.cornerRadius = 8;
    mapview.layer.masksToBounds = YES;
    [mapview release];
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10, 16, self.view.frame.size.width * 2 / 3, 30)];
    self.searchBar.placeholder = @"请输入地名";
    self.searchBar.delegate = self;
    self.searchBar.layer.cornerRadius = 8;
    self.searchBar.layer.masksToBounds = YES;
    
    self.searchBar.showsCancelButton = YES;
    self.searchBar.barStyle = UIBarStyleDefault;
    self.searchBar.keyboardType = UIKeyboardTypeDefault;
    [mapview addSubview:self.searchBar];
    [self.searchBar release];
    
    
    self.mview = [[UIView alloc] initWithFrame:CGRectMake(20 * _offWidth, 130 * _offHeight, 300 * _offWidth, 100 *_offHeight)];
    
    _mview.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_mview];
    
    
    self.locallabel= [[UILabel alloc] initWithFrame:CGRectMake(20 * _offWidth, 100 * _offHeight, 120 * _offWidth, 30 * _offHeight)];
    _locallabel.backgroundColor = [UIColor clearColor];
    _locallabel.text = @"当地天气为:";
    _locallabel.font = [UIFont systemFontOfSize:20];
    _locallabel.textColor = [UIColor grayColor];
    [self.view addSubview:_locallabel];
    
    
    self.cclabel = [[UILabel alloc] initWithFrame:CGRectMake(65 * _offWidth, 10, 30, 30)];
    _cclabel.text = @"~";
    _cclabel.font = [UIFont systemFontOfSize:30];
    _cclabel.backgroundColor = [UIColor clearColor];
    [_mview addSubview:_cclabel];
    
    
    self.xbutton = [UIButton buttonWithType:UIButtonTypeSystem];
    [_xbutton setTitle:@"详情" forState:UIControlStateNormal];
    _xbutton.frame = CGRectMake(150 * _offWidth, 0, 42, 32);
    _xbutton.titleLabel.font = [UIFont systemFontOfSize:20];
    [_xbutton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_mview addSubview:_xbutton];
    
    
    self.maxlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0,50, 50)];
    _maxlabel.backgroundColor = [UIColor clearColor];
    //  self.maxlabel.text = @"";
    _maxlabel.textColor= [ UIColor grayColor];
    _maxlabel.font = [UIFont systemFontOfSize:40];
    [_mview addSubview:_maxlabel];
    
    
    
    self.minlabel = [[UILabel alloc] initWithFrame:CGRectMake(90 * _offWidth, 0,50, 50)];
    _minlabel.backgroundColor = [UIColor clearColor];
    //   self.minlabel.text = @"";
    _minlabel.textColor= [ UIColor grayColor];
    _minlabel.font = [UIFont systemFontOfSize:40];
    [_mview addSubview:_minlabel];
    
    self.weatherlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 50 * _offHeight,100, 50)];
    _weatherlabel.backgroundColor = [UIColor colorWithWhite:0.7 alpha:0.7];
    self.weatherlabel.text = @"";
    _weatherlabel.numberOfLines = 0;
    _weatherlabel.backgroundColor = [UIColor clearColor];
    _weatherlabel.layer.cornerRadius = 8;
    _weatherlabel.layer.masksToBounds = YES;
    _weatherlabel.textColor= [ UIColor grayColor];
    _weatherlabel.font = [UIFont systemFontOfSize:20];
    [_mview addSubview:_weatherlabel];
    
    self.flabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 105 * _offHeight,100, 50)];
    _flabel.backgroundColor = [UIColor colorWithWhite:0.7 alpha:0.7];
    self.flabel.text = @"";
    _flabel.numberOfLines = 0;
    _flabel.backgroundColor = [UIColor clearColor];
    _flabel.layer.cornerRadius = 8;
    _flabel.layer.masksToBounds = YES;
    _flabel.textColor= [ UIColor grayColor];
    _flabel.font = [UIFont systemFontOfSize:20];
    [_mview addSubview:_flabel];
    
    
    self.maxlabel.hidden = YES;
    self.minlabel.hidden = YES;
    self.weatherlabel.hidden = YES;
    self.flabel.hidden = YES;
    self.xbutton.hidden = YES;
    self.locallabel.hidden = YES;
    
    self.cclabel.hidden = YES;
    
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//    [button setTitle:@"天气" forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"iconfont-qing.png"] forState:UIControlStateNormal];
    button.frame = CGRectMake(300 * _offWidth, 0, 30, 30);
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[ UIBarButtonItem alloc] initWithCustomView:button];
    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    
    
}

- (void)button:(UIButton *)button
{
    _b = _b * (-1);
    if (self.arr.count != 0) {
    
    
    
    if (_b == -1) {
        
        
        
        self.maxlabel.hidden = NO;
        self.minlabel.hidden = NO;
        self.weatherlabel.hidden = NO;
        self.flabel.hidden = NO;
        self.xbutton.hidden = NO;
        self.locallabel.hidden = NO;
        
        self.cclabel.hidden = NO;
        
        
        
        
    }
    
    else
    {
        [_alabel removeFromSuperview];
        [_blabel removeFromSuperview];
        [_clabel removeFromSuperview];
        [_dlabel removeFromSuperview];
        self.maxlabel.hidden = YES;
        self.minlabel.hidden = YES;
        self.weatherlabel.hidden = YES;
        self.flabel.hidden = YES;
        self.xbutton.hidden = YES;
        self.locallabel.hidden = YES;
       
        self.cclabel.hidden = YES;
        
        
        if (_a == -1) {
            _a =1;
        }
        else
        {
            _a = 1;
        }
        
    }
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请搜索地名" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}


//搜索方法
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    
   
    
    searchBar.showsCancelButton = YES;
    
    
    
    return YES;
}


#pragma mark - 结束编辑取消键消失
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
   
    searchBar.showsCancelButton = NO;
    //   [self getCoordinateByAddress:self.searchtext];
    
    
}
#pragma mark - 搜索的文字
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    
    
    [self.arr removeAllObjects];
    self.localstr = nil;

    
 
    
    if ([searchBar.text isEqualToString:@"大连"]) {
        searchBar.text = @"大连市";
    }
    [self getCoordinateByAddress:searchBar.text];
    [searchBar resignFirstResponder];
    
    
    self.searchtext = searchBar.text;
    
  
    [self addData];
    
    [_alabel removeFromSuperview];
    [_blabel removeFromSuperview];
    [_clabel removeFromSuperview];
    [_dlabel removeFromSuperview];
    self.maxlabel.hidden = YES;
    self.minlabel.hidden = YES;
    self.weatherlabel.hidden = YES;
    self.flabel.hidden = YES;
    self.xbutton.hidden = YES;
    self.locallabel.hidden = YES;
    
    self.cclabel.hidden = YES;
    _a = 1;
    _b = 1;
    
}
#pragma mark - 按取消键清除文字
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
  
    searchBar.text = @"";
    [searchBar resignFirstResponder];
}




- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    
 
    
    //  NSLog(@"latitude : %f,longitude:%f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        currentPoint = [[MAPointAnnotation alloc] init];
        currentPoint.coordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude,userLocation.coordinate.longitude);
        [self.mapView addAnnotation:currentPoint];
        [currentPoint release];
    });
    //  userLocation.location.description.pathComponents  时间数组
    NSLog(@"wer = %@",userLocation.location.description.pathComponents );
    
}

//大头针
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    
    static NSString *ident = @"cell";
    MAPinAnnotationView *ann = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:ident];
    if (ann == nil) {
        ann = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ident];
    }
    ann.canShowCallout = YES;
    ann.animatesDrop = YES;
    ann.draggable = YES;
    ann.pinColor = MAPinAnnotationColorPurple;
    
    return ann;
    
}

#pragma mark -
#pragma mark 地址解析定位

//根据地名解析坐标
- (void)getCoordinateByAddress:(NSString *)address
{
    
    
    
    
    [self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
        NSLog(@"水电费 = %lu",(unsigned long)placemarks.count);
        //取得第一个地标，地标中存储了详细的地址信息，注意：一个地名可能搜索出多个地址
        CLPlacemark *placemark = [placemarks firstObject];
      //  NSLog(@" 爱疯= %@",placemark);
        //位置
        CLLocation *location = placemark.location;
        
        
     //   NSLog(@"经度 = %f",location.coordinate.longitude);
     //   NSLog(@"纬度 = %f",location.coordinate.latitude);
#pragma mark -
#pragma mark 大头针
        
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
        annotation.coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
        annotation.title = @"位置";
        //  annotation.subtitle = [NSString stringWithFormat:@"%@-%@-%@",placemark.administrativeArea,placemark.locality,placemark.subLocality];
        [_mapView addAnnotation:annotation];
        [self.mapView selectAnnotation:annotation animated:YES];
        
    }];
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end